package pers.hl.lib_global.http

import com.blankj.utilcode.util.LogUtils
import com.google.gson.Gson
import okhttp3.*
import okhttp3.ResponseBody.Companion.toResponseBody
import org.json.JSONObject
import pers.hl.common.http.BaseInterceptor
import pers.hl.lib_global.model.bean.DoubanBook

/**
 * 豆瓣接口拦截器，由于豆瓣api返回格式不同，主要用于重构返回数据
 */
class DouBanInterceptor: BaseInterceptor() {

    override fun needIntercept(request: Request): Boolean {
        request.apply {
            val originUrl = url.toString()
            return originUrl.contains("douban")
        }
    }

    /**
     * 经测试，豆瓣图书接口只有微信请求不受apikey访问限制，模拟微信,copy userAgent,
     * 移除原有header,加入相同header,重新构造请求.
     *
     * User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36 QBCore/4.0.1316.400 QQBrowser/9.0.2524.400 Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2875.116 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat
     */
    private fun mockWechatHeaderResponse(chain: Interceptor.Chain, request: Request): Response {
        val wechatUserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36 QBCore/4.0.1316.400 QQBrowser/9.0.2524.400 Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2875.116 Safari/537.36 NetType/WIFI MicroMessenger/7.0.20.1781(0x6700143B) WindowsWechat"
        val originUserAgent = request.header("User-Agent")
        LogUtils.d(TAG, "原始User-Agent：$originUserAgent")
        val newRequest = request.newBuilder()
            .removeHeader("User-Agent")
            .addHeader("User-Agent", wechatUserAgent)
            .build()
        return chain.proceed(newRequest)
    }

    override fun doIntercept(chain: Interceptor.Chain, request: Request): Response {
        val newResponse = mockWechatHeaderResponse(chain, request)
        val body = newResponse.body
        body?.apply {
            val bodyValue = body.string()
            val gson = Gson()
            val contentType = body.contentType()
           if (newResponse.code == 200) {
               val result = gson.fromJson(bodyValue, DoubanBook::class.java)
               val jsonObject = JSONObject()
               jsonObject.put("code", 200)
               jsonObject.put("msg", "成功")
               jsonObject.put("data", bodyValue)
               val finalBody = jsonObject.toString().toResponseBody(contentType)
               LogUtils.d("豆瓣返回数据")
               return newResponse.newBuilder().body(finalBody).build()
           } else {
               val result = gson.fromJson(bodyValue, DouBanErrorResponse::class.java)
               val jsonObject = JSONObject()
               jsonObject.put("code", result.code)
               jsonObject.put("msg", result.msg)
               jsonObject.put("data", result.request)
               val finalBody = jsonObject.toString().toResponseBody(contentType)
               LogUtils.d("豆瓣接口错误")
               return newResponse.newBuilder().body(finalBody).build()
           }
        }
        return newResponse
    }
}